import { Injectable, UnauthorizedException } from '@nestjs/common'
import { UserService } from '../user/user.service'
import { JwtService } from '@nestjs/jwt'
import { LoginDto } from './auth.dto'
import { jwtConstants } from './constants'

@Injectable()
export class AuthService {
  constructor(
    private usersService: UserService,
    private jwtService: JwtService,
  ) {}

  async login(loginParams: LoginDto): Promise<any> {
    const { username, password } = loginParams
    const user = await this.usersService.findUser(username)
    if (user?.password !== password) {
      throw new UnauthorizedException()
    }

    const payload = { ...user }
    const token = await this.jwtService.signAsync(payload)
    return {
      token: jwtConstants.tokenPrefix + token,
    }
  }
}
